import React, { useMemo } from 'react';
import cn from 'classnames';
import styles from './index.less';

type content = () => React.ReactElement;

interface Props {
    label: string | content;
    value: string | content;
    className?: string;
    layout?: 'horizontal' | 'vertical';
    colon?: boolean;
    align?: 'top' | 'center' | 'bottom';
    requiredMark?: boolean;
    style?: React.CSSProperties;
    labelClassName?: string;
    labelStyle?: React.CSSProperties;
    valueClassName?: string;
    valueStyle?: React.CSSProperties;
    formLayout?: boolean;
}

const LabelValue = React.memo(
    ({
        label,
        value,
        className,
        layout = 'horizontal',
        colon = true,
        align = 'center',
        requiredMark = false,
        style,
        labelClassName,
        labelStyle,
        valueClassName,
        valueStyle
    }: Props) => {
        const computeClass = useMemo(
            () =>
                cn(
                    styles.labelValue,
                    `${layout === 'horizontal' ? styles.labelValueHorizontal : styles.labelValueVertical}`,
                    `label-value-flex-${align}`,
                    `${className || ''}`
                ),
            [align, className, layout]
        );

        return (
            <div className={computeClass} style={style}>
                <div className={cn(styles.labelValueKey, `${labelClassName || ''}`)} style={labelStyle}>
                    <span className={styles.labelValueKeyRequired}>{requiredMark ? '*' : ''}</span>
                    <span>{typeof label === 'function' ? label() : label}</span>
                    <span className={styles.labelValueKeyColon}>{colon ? ':' : ''}</span>
                </div>
                {typeof value === 'function' ? (
                    <div className={cn(styles.labelValueValue, `${valueClassName || ''}`)} style={valueStyle}>
                        {value()}
                    </div>
                ) : (
                    <div
                        className={cn(styles.labelValueValue, `${valueClassName || ''}`)}
                        style={style}
                        // eslint-disable-next-line react/no-danger
                        dangerouslySetInnerHTML={{
                            __html: !value ? '--' : value?.replace(/[\r\n]+/g, '<br />')
                        }}
                    ></div>
                )}
            </div>
        );
    }
);

export default LabelValue;
